<template>
	<view class="content">
		<view class="app-title">
			<view class="app-title-item">
				<image class="back" src="/static/img/back.png" @click="back"></image>
				<text>设备监测信息</text>
			</view>
		</view>

		<view class="content-curve">
			<div class="select-section">
				<!-- 车站选择 -->
				<view class="select-item" @click="openSelect(1)">
					<view>车站选择</view>
					<view class="select-val">{{station.name || '请选择'}}</view>
				</view>
				<!-- 设备类型 -->
				<view class="select-item" @click="openSelect(2)">
					<view>设备类型</view>
					<view class="select-val">{{deviceType.name || '请选择'}}</view>
				</view>
				<div class="btn">
					<button class="default-btn" @click="queryDevs">
						<b>刷新</b>
					</button>
				</div>
				<!-- 选择器 -->
				<u-select v-model="selectShow" :list="selectList" v-bind="selectOptions"
					@confirm="selectConfirm"></u-select>
			</div>

			<!-- 表格 -->
			<div class="table-section">
				<u-table>
					<u-tr>
						<u-th width="45px">序号</u-th>
						<u-th width="150px">设备名</u-th>
						<u-th width="100px" v-for="(item,index) in tableHead" :key="index">{{item}}</u-th>
					</u-tr>
					<u-tr v-for="(item,index) in tableData" :key="item.equId">
						<u-td width="45px">{{index + 1}}</u-td>
						<u-td width="150px">
							<view class="link" @click="onDetail(item)">
								{{item.equName}}
							</view>
						</u-td>
						<u-td width="100px" v-for="(cItem,cIndex) in item.equTCjx"
							:key="cIndex">{{cItem.dataVal}}</u-td>
					</u-tr>
				</u-table>
			</div>
			<u-empty v-if="!tableData.length" mode="data"></u-empty>
		</view>
		<u-mask :show="loading">
			<view class="loading-warp">
				<u-loading mode="circle" size="70"></u-loading>
			</view>
		</u-mask>
	</view>
</template>

<script>
	import dayjs from "../../static/plugins/js/dayjs/dayjs.min.js";

	export default {
		data() {
			return {
				pageType: '',
				// 信号机、道岔、轨道电路 code
				equTypeCode: '',
				equTypeId: "",
				// 选择
				selectShow: false,
				selectList: [],
				selectOptions: {},
				selectType: '',
				// 车站
				station: {
					name: '',
					code: '',
				},
				stationList: [],
				// 设备类型
				deviceType: {
					name: '',
					code: '',
				},
				deviceTypeList: [],
				// 表格
				tableData: [],
				tableHead: [],
				loading: false
			}
		},
		onLoad(options) {
			// 响应式数据、计算属性、方法、侦听器、props、slots 已设置完成

			console.log('设备监测信息::onload::', dayjs().format('YYYY-MM-DD HH:mm:ss'), options);

			this.pageType = options.type;

			// 菜单对应类型的code
			this.equTypeCode = options.code
			this.equTypeId = options.id
		},
		onShow() {
			// 页面每次出现在屏幕上都触发
		},
		async onReady() {
			// 初次渲染完成，组件已挂载，dom可用
			try {
				await this.queryStation()
				await this.queryEquipment()
				// await this.queryDevs()
			} catch (e) {
				//TODO handle the exception
			}
		},
		// onReachBottom
		methods: {
			// 查询车站列表
			async queryStation() {
				const config = {
					url: '/api/sys/station/getStationsByLineIdType',
					params: {
						orgId: this.$store.state.userInfo?.org.idK,
						type: '车站'
					}
				}

				try {
					await this.fetch(
						"get",
						this.$store.state.baseUrl + config.url,
						config.params,
						false
					).then((res) => {
						const {
							data
						} = res
						if (data && data.length) {
							this.stationList = data
							if (!this.station.code && data.length == 1) {
								const {
									code,
									name
								} = data[0]
								this.station = {
									name: name,
									code: code,
								}
							}
						} else {
							this.stationList = []
						}
					})
				} catch (e) {
					//TODO handle the exception
				}
			},
			// 查询设备类型列表
			async queryEquipment() {
				if (!this.station.code) return
				this.deviceTypeList = [];
				this.deviceType = {
					name: "",
					code: ""
				}
				const config = {
					url: '/api/equType/getTypeTree',
					params: {
						equTypeCode: this.equTypeCode,
						stationCode: this.station.code,
						vtype: '1E'
					}
				}

				try {
					await this.fetch(
						"get",
						this.$store.state.baseUrl + config.url,
						config.params,
						false
					).then((res) => {
						const {
							data
						} = res
						if (data && data.length) {
							this.deviceTypeList = data
							// if (!this.deviceType.code && this.deviceTypeList.length == 1) {
							// 	const code = this.findLastChildCode(data[0])
							// 	const {
							// 		path
							// 	} = this.findLastChildWithCode(data, code)
							// 	this.deviceType = {
							// 		name: path.map(item => item.text).join('/'),
							// 		code: code
							// 	}
							// }
							if(!this.deviceType.code && (this.deviceTypeList.length == 1 && this.deviceTypeList[0].children?.length == 1) || (this.deviceTypeList.length == 1 && !this.deviceTypeList[0].children)) {
								const code = this.findLastChildCode(data[0])
								const {
									path
								} = this.findLastChildWithCode(data, code)
								this.deviceType = {
									name: path.map(item => item.text).join('/'),
									code: code
								}
								this.queryDevs();
							}
						} else {
							this.deviceTypeList = []
						}
					})
				} catch (e) {
					//TODO handle the exception
				}
			},
			// 设备列表 
			queryDevs() {
				if (!this.station.code || !this.deviceType.code) return
				const params = {
					station: this.station.code,
					equtype: this.deviceType.code
				}
				this.loading = true
				this.fetch(
					"get",
					this.$store.state.baseUrl + '/api/equ/getEquDevCjxRealData',
					params,
					false
				).then((res) => {
					const {
						data
					} = res
					if (data && data.length) {
						this.tableData = data
						this.tableHead = this.tableData[0].equTCjx.map(item => item.dataName)
					} else {
						this.tableData = []
					}
				}).finally(() => {
					this.loading = false
				})
			},
			// 打开选择器
			async openSelect(val) {
				if (!val) return

				this.selectList = []
				this.selectOptions = {}
				this.selectType = val

				// 车站
				if (val == 1) {
					await this.queryStation()
					this.selectList = this.stationList
					this.selectOptions = {
						mode: 'single-column',
						valueName: 'code',
						labelName: 'name',
					}
				}

				// 设备
				if (val == 2) {
					// await this.queryEquipment()
					this.selectList = this.deviceTypeList
					this.selectOptions = {
						mode: 'mutil-column-auto',
						valueName: 'code',
						labelName: 'text',
					}
				}

				if (!this.selectList.length) return

				this.selectShow = true
			},
			// 选择器选择
			selectConfirm(e) {
				// 车站
				if (this.selectType == 1) {
					this.station.name = e[e.length - 1].label
					this.station.code = e[e.length - 1].value
					this.queryEquipment()
				}
				// 设备
				if (this.selectType == 2) {
					this.deviceType.name = e.map(item => item.label).join('/')
					this.deviceType.code = e[e.length - 1].value
				}
				this.queryDevs()
			},
			// 详情
			onDetail(row) {
				uni.navigateTo({
					url: `/pages/monitorCurve/detail?code=${this.station.code}&id=${row.equId}&equTypeId=${this.equTypeId}&equName=${row.equName}`
				});
			},
			// 返回
			back() {
				uni.navigateTo({
					url: "/pages/index/index",
				});
			},
			findLastChildCode(obj) {
				if (obj.children && Array.isArray(obj.children) && obj.children.length >
					0) {
					return this.findLastChildCode(obj.children[obj.children.length - 1]);
				} else {
					return obj.code;
				}
			},
			findLastChildWithCode(arr, targetCode, path = []) {
				let foundItem = null;
				for (const item of arr) {
					path.push(item);
					if (item.code === targetCode && (!item.children || !Array.isArray(item
							.children) || item.children.length === 0)) {
						foundItem = {
							item,
							path
						};
						break;
					} else if (item.children && Array.isArray(item.children)) {
						const deeperResult = this.findLastChildWithCode(item.children,
							targetCode, path.slice());
						if (deeperResult) {
							foundItem = deeperResult;
							break;
						}
					}
					path.pop();
				}
				return foundItem;
			}
		}
	}
</script>

<style scoped lang="less">
	.content {
		width: 100%;
		height: 100vh;
		background: #fff;
		position: fixed;

		display: flex;
		flex-direction: column;

		.app-title {
			text-align: center;

			.app-title-item {
				position: relative;
			}

			.back {
				position: absolute;
				top: 50%;
				left: 0;
				transform: translateY(-50%);
			}
		}

		.content-curve {
			height: 0;
			flex: 1;
			flex-basis: 0;

			display: flex;
			flex-direction: column;

			.select-section {
				padding: 5px 0;
				background: #f3f3f3;
				.btn {
				  margin: 5px 5px 0 0; 
					display: flex;
					justify-content: flex-end;
				  .default-btn {
				    width: 80px;
				  }
				}
			}

			.select-item {
				padding: 12px 18px;
				background: #fff;

				display: flex;
				align-items: center;

				&+.select-item {
					border-top: 1px solid #eee;
				}

				.select-val {
					width: 0;
					flex: 1;
					flex-basis: 0;

					text-align: right;
				}
			}

			.table-section {
				height: 0;
				flex: 1;
				flex-basis: 0;
				overflow: auto;
			}
		}
	}

	.link {
		color: blue;
		text-decoration: underline;
	}

	.loading-warp {
		height: 98vh;

		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>